package com.brillilab.service.core.email.impl;

import com.brillilab.common.redis.RedisCache;
import com.brillilab.common.utils.CodeUtil;
import com.brillilab.common.utils.EmailSendUtil;
import com.brillilab.service.constant.ServiceConstant;
import com.brillilab.service.core.email.IEmailService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 邮件服务实现类
 *
 * @author wmh
 */
@Slf4j
@Data
@Service
@ConfigurationProperties(prefix="email")
public class EmailServiceImpl implements IEmailService {
	@Autowired
	private RedisCache redisCache;
    private String smtp;
    private String port;
    private String user;
    private List<String> users;
    private String password;
    private String sendUserName;
    //private List<String> learningEmailSuffixList;

    private ConcurrentHashMap<String, AtomicInteger> emailCountMap=new ConcurrentHashMap<>(10);
    private ConcurrentHashMap<String, Date> emailSendTimeMap=new ConcurrentHashMap<>(10);

    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @Override
    public boolean sendValidateCode(String email) {
        Assert.isTrue(!sendTimeConfirm(email), "验证码发送太过频繁,5分钟后再尝试!");
        try {
            String code= CodeUtil.getCode(6,"1234567890");

            EmailSendUtil emailSender=this.getEmailSender();
            String title="【LabInOne】 邮箱身份验验证码";
            String sendHtml="<p>您的验证码是:  " + code + "  ，您正在进行身份校验，请不要将验证码告诉他人！</p>";

            redisCache.set(ServiceConstant.email_verify_code + email,code,300);

            emailSendTimeMap.put(email,new Date());

            return emailSender.sendHtmlEmail(title,sendHtml,email);
        } catch (Exception e) {
            log.error("邮件发送服务异常:",e);
            return false;
        }

    }

    /**
     * 发送次数不能多于5次 多于5次5分钟后才能发送
     *
     * @param email
     * @return
     */
    @SuppressWarnings("unused")
	private boolean sendTimeConfirm(String email) {
        AtomicInteger count=emailCountMap.get(email);
        if(count == null){
            emailCountMap.put(email,new AtomicInteger(1));
            return false;
        }
        if(count.get() >= 5){
            //5分钟以后能重新发送
            Date last=emailSendTimeMap.get(email);
            if((new Date().getTime()-last.getTime())>5*60*1000){
                emailCountMap.put(email,new AtomicInteger(1));
                return false;
            }
            return true;
        }
        count.getAndAdd(1);
        return false;
    }

    public EmailSendUtil getEmailSender() {
        Random random = new Random();
        //随机获取发送邮箱地址
        String sendUser=users.get(random.nextInt(users.size()));
        return new EmailSendUtil(smtp,port,sendUser,password,sendUserName);
    }
}
